import Taro, { useEffect, useState } from '@tarojs/taro'
import {Image, View, Button, Canvas} from '@tarojs/components'
// import drawQrcode from 'weapp-qrcode'
import qrcode from '../../utils/qrcode'
import './index.scss'

// api
import api from '../../api/index';
import getAvatarImgPrefix from "../../utils/getAvatarImgPrefix";

export default function Poster({ user = {}, visible = false, onCancel }) {
  const posters = ['https://res.read1000.com/poster/invitation/01@3x.jpg']
  const [url, setUrl] = useState('')
  const [qrCode, setQrCord] = useState('')
  const [posterUrl, setPosterUrl] = useState('')

  useEffect(async () => {
    const data = await api.user.getInvitationCode()
    if(data.code > 0) {
      console.log(user)
      setUrl(encodeURI(`https://www.read1000.com/Introduce/Present.html?user=${user.user.nickname}&code=${data.data}&orgid=${user.user.organization.org_id}`))
    }
  }, [])

  useEffect(async () => {
    if (url) {
      console.log('url', url)
      const _this = this
      // const avatar = user.user.avatar_url ? getAvatarImgPrefix(user.user.avatar_url) : require('../../assets/180x180defalut_avatar@2x.png')
      let avatar = ''

      if(user.user.avatar_url) {
        const res = await Taro.getImageInfo({
          src: getAvatarImgPrefix(user.user.avatar_url)
        })
        avatar = res.path
      } else {
        avatar = require('../../assets/180x180defalut_avatar@2x.png')
      }

      qrcode.api.draw(url, {
        ctx: Taro.createCanvasContext('myQrcode', _this.$scope),
        width: 200,
        height: 200,
        background: '#fff',
        logo: avatar,
        callback: () => {
          Taro.canvasToTempFilePath({
            canvasId: 'myQrcode',
            success: (res) => {
              console.log(res.tempFilePath)
              setQrCord(res.tempFilePath)
            },
            fail: (err) => {
              console.log(err)
            }
          }, _this.$scope)
        },
      })


      // Taro.getImageInfo({
      //   src: avatar
      // }).then(res => {
      //   console.log(res)
      //
      //   qrcode.api.draw(url, {
      //     ctx: Taro.createCanvasContext('myQrcode', _this.$scope),
      //     width: 200,
      //     height: 200,
      //     background: '#fff',
      //     logo: res.path,
      //     callback: () => {
      //       Taro.canvasToTempFilePath({
      //         canvasId: 'myQrcode',
      //         success: (res) => {
      //           console.log(res.tempFilePath)
      //           setQrCord(res.tempFilePath)
      //         },
      //         fail: (err) => {
      //           console.log(err)
      //         }
      //       }, _this.$scope)
      //     },
      //   })
      // }).catch(err => {
      //   console.log('asdfs')
      // })


      // Taro.getImageInfo({
      //   src: avatar
      // }).then((res) => {
      //   drawQrcode({
      //     width: 200,
      //     height: 200,
      //     canvasId: 'myQrcode',
      //     text: url,
      //     _this: _this.$scope,
      //     correctLevel: 2,
      //     image: {
      //       imageResource: res.path,
      //       dx: 70,
      //       dy: 70,
      //       dWidth: 60,
      //       dHeight: 60
      //     },
      //     callback: () => {
      //       Taro.canvasToTempFilePath({
      //         canvasId: 'myQrcode',
      //         success: (res) => {
      //           console.log(res.tempFilePath)
      //           // Taro.saveImageToPhotosAlbum({
      //           //   filePath: res.tempFilePath
      //           // })
      //           setQrCord(res.tempFilePath)
      //         },
      //         fail: (err) => {
      //           console.log(err)
      //         }
      //       }, _this.$scope)
      //     },
      //   })
      // })
    }
  }, [url])

  useEffect(() => {
    const _this = this
    // const CANVAS_WIDTH = 1125
    // const CANVAS_HEIGHT = 2001
    const CANVAS_WIDTH = 750
    const CANVAS_HEIGHT = 1334
    const QRCODE_WIDTH = 180
    const QRCODE_HEIGHT = 180

    if (qrCode) {
      console.log(123123123)

      Taro.getImageInfo({
        src: posters[0]
      }).then((res) => {
        const ctx = Taro.createCanvasContext('myPoster', _this.$scope);
        ctx.drawImage(res.path, 0,0 , CANVAS_WIDTH, CANVAS_HEIGHT)
        ctx.drawImage(qrCode, 64 ,1124 , QRCODE_WIDTH, QRCODE_HEIGHT)
        ctx.setFontSize(28)
        ctx.setFillStyle('#fff000')
        ctx.fillText(`${user.user.nickname}邀请你`, 64 + 180 + 24, 1124 + 10 + 24)
        ctx.setFontSize(32)
        ctx.setFillStyle('#ffffff')
        ctx.fillText('扫码下载千读APP一起学英语', 64 + 180 + 24, 1124 + 10 + 24 + 28 + 20)
        ctx.fillText('点读 · 配音 · 评分 · 习题', 64 + 180 + 24, 1124 + 10 + 24 + 28 + 20 + 32 + 20)
        ctx.draw(false, () => {
          Taro.canvasToTempFilePath({
            canvasId: 'myPoster',
            success: (resonse) => {
              setPosterUrl(resonse.tempFilePath)
            },
          }, _this.$scope)
        })
      })
    }
  }, [qrCode])

  useEffect(() => {
    if (visible) {
      console.log('123123')
      if (posterUrl) {
        console.log('a123123')
        Taro.hideLoading()
      } else {
        console.log('b123123')
        Taro.showLoading()
      }
    }
  }, [posterUrl, visible])


  function saveImage() {
    if (posterUrl) {
      Taro.saveImageToPhotosAlbum({
        filePath: posterUrl
      }).then(() => {
        Taro.showToast({
          title: '海报保存成功'
        })
      }).catch(err => {
        if (err.errMsg.indexOf('cancel')) {
          Taro.showToast({
            title: '取消保存',
            icon: 'none'
          })
        } else if (err.errMsg.indexOf('auth')) {
          Taro.showToast({
            title: '无法获得保存相册权限，请允许授权后再保存图片！',
            icon: 'none'
          })
        }


      })
    }
  }

  return (
    <View className={`poster-container ${visible ? 'show' : '' }`}>
      <Canvas style='width: 200px; height: 200px;' canvas-id='myQrcode' className='code-canvas' />
      <Canvas style='width: 750px; height: 1334px;' canvas-id='myPoster' className='poster-canvas' />
      <View className='poster-wrapper'>
        <Image
          src={require('../../assets/cancel36X36@2x.png')}
          className='close'
          onClick={() => onCancel()}
        />
        <View className='title'>分享海报</View>
        <View
          className='poster'
        >
          <Image
            className='img'
            src={posterUrl}
          />
        </View>

        <Button className='btn' onClick={() => saveImage()}>保存图片</Button>
      </View>
    </View>
  )
}

